package com.miao.edu.user.remote;

import cn.hutool.core.collection.CollectionUtil;
import com.miao.edu.user.api.UserRemoteService;
import com.miao.edu.user.dto.UserDTO;
import com.miao.edu.user.entity.User;
import com.miao.edu.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserRemoteServiceImpl implements UserRemoteService {

    @Autowired
    private IUserService userService;


    /**
     * 密码编码解码器
     */
    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public boolean isRegister(String phone) {
        UserDTO userByPhone = this.getUserByPhone(phone);
        return userByPhone !=null && !Boolean.TRUE.equals(userByPhone.getIsDel());
    }

    @Override
    public UserDTO getUserByPhone(String phone) {
        List<User> list = this.userService.lambdaQuery().eq(User::getPhone, phone).orderByDesc(User::getId).list();
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(list.get(0),userDTO);
        return userDTO;
    }

    @Override
    public UserDTO saveUser(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        System.out.println(userDTO.getPassword());
        //设置密码
        user.setPassword(encoder.encode(userDTO.getPassword()));
        // 设置用户昵称
        if (StringUtils.isNotBlank(user.getPhone())) {
            // 如果用户手机不为空的话，试用新用户 + 手机号码组成用户昵称
            user.setName("新用户" +"_"+user.getPhone().substring(user.getPhone().length() - 4));
        }

        // 保存用户信息
        this.userService.save(user);
        BeanUtils.copyProperties(user,userDTO);
        log.info("用户[{}]添加成功",userDTO);
        return userDTO;
    }

    @Override
    public UserDTO getUserById(Integer userId) {
        User byId = this.userService.getById(userId);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(byId,userDTO);
        return userDTO;
    }


}
